package com.tanhua.manager.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.manager.domain.Log;
import com.tanhua.manager.domain.AnalysisByDay;
import com.tanhua.manager.domain.AnalysisChartDataItem;
import com.tanhua.manager.domain.AnalysisSummaryVO;
import com.tanhua.manager.mapper.LogMapper;
import com.tanhua.manager.mapper.SummaryMapper;
import com.tanhua.manager.utils.ComputeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class SummaryService {
    @Autowired
    private SummaryMapper summaryMapper;
    @Autowired
    private LogMapper logMapper;
    public ResponseEntity summary() {

        AnalysisSummaryVO vo = new AnalysisSummaryVO();
        //cumulativeUsers   累计用户
        long cumulativeUsers = summaryMapper.cumulativeUsers();
        vo.setCumulativeUsers(cumulativeUsers);
        //activePassMonth    过去30天活跃用户
        DateTime today = DateUtil.beginOfDay(new Date());
        DateTime date30 = DateUtil.offsetDay(today, -30);
        long activePassMonth  = summaryMapper.activePassMonth(date30,today);
        vo.setActivePassMonth(activePassMonth);
        //activePassWeek	过去7天活跃用户
        DateTime date7 = DateUtil.offsetDay(today, -7);
        long activePassWeek  = summaryMapper.activePassMonth(date7,today);
        vo.setActivePassWeek(activePassWeek);
        //newUsersToday	  今日新增用户
        AnalysisByDay analysisByDay = summaryMapper.selectOne(new LambdaQueryWrapper<AnalysisByDay>().eq(AnalysisByDay::getRecordDate, today));
        Integer newUsersToday = analysisByDay.getNumRegistered();
        vo.setNewUsersToday(newUsersToday.longValue());


        //newUsersTodayRate	   今日新增用户涨跌率
        DateTime yesterday = DateUtil.offsetDay(today, -1);
        AnalysisByDay yesterdayUsers = summaryMapper.selectOne(new LambdaQueryWrapper<AnalysisByDay>().eq(AnalysisByDay::getRecordDate, yesterday));
        BigDecimal newUsersTodayRate = ComputeUtil.computeRate(newUsersToday.longValue(), yesterdayUsers.getNumRegistered().longValue());
        vo.setNewUsersTodayRate(newUsersTodayRate);


        //loginTimesToday	今日登录次数
        Integer loginTimesToday = analysisByDay.getNumLogin();
        vo.setLoginTimesToday(loginTimesToday.longValue());
        //loginTimesTodayRate	今日登录次数涨跌率
        BigDecimal loginTimesTodayRate = ComputeUtil.computeRate(loginTimesToday.longValue(), yesterdayUsers.getNumLogin().longValue());
        vo.setLoginTimesTodayRate(loginTimesTodayRate);
        //activeUsersToday	今日活跃用户
        Integer activeUsersToday = analysisByDay.getNumActive();
        vo.setActiveUsersToday(activeUsersToday.longValue());
        //activeUsersTodayRate	今日活跃用户涨跌率
        BigDecimal activeUsersTodayRate = ComputeUtil.computeRate(activeUsersToday.longValue(), yesterdayUsers.getNumLogin().longValue());
        vo.setActiveUsersTodayRate(activeUsersTodayRate);
        return ResponseEntity.ok(vo);
    }

    /**
     * GET/dashboard/users
     * 新增、活跃用户、次日留存率  折线图
     * @param sd    开始时间
     * @param ed    结束时间
     * @param type 101 新增 102 活跃用户 103 次日留存率
     * @return
     */
    public ResponseEntity usersChartData(Long sd, Long ed, Integer type) {
        DateTime thisYearBegin = DateUtil.beginOfDay(new Date(sd));
        DateTime thisYearEnd = DateUtil.endOfDay(new Date(ed));
        DateTime lastYearBegin = DateUtil.offset(thisYearBegin, DateField.YEAR, -1);
        DateTime lastYearEnd = DateUtil.offset(thisYearEnd, DateField.YEAR, -1);
        List<AnalysisByDay> thisYearAnalysis = summaryMapper.selectList(new LambdaQueryWrapper<AnalysisByDay>().between(AnalysisByDay::getRecordDate, thisYearBegin, thisYearEnd));
        List<AnalysisByDay> lastYearAnalysis = summaryMapper.selectList(new LambdaQueryWrapper<AnalysisByDay>().between(AnalysisByDay::getRecordDate, lastYearBegin, lastYearEnd));
        ArrayList<AnalysisChartDataItem> thisYearItems = new ArrayList<>();
        for (AnalysisByDay analysis : thisYearAnalysis) {
            AnalysisChartDataItem item = new AnalysisChartDataItem();
            Integer data = 0;
            String date = DateUtil.format(analysis.getRecordDate(), "yyyy-MM-dd");
            if (type == 101){
                data = analysis.getNumRegistered();
            }else if (type ==102){
                data = analysis.getNumActive();
            }else if (type ==103){
                data = analysis.getNumRetention1d();
            }
            item.setAmount(data.longValue());
            item.setTitle(date);
            thisYearItems.add(item);
        }
        ArrayList<AnalysisChartDataItem> lastYearItems = new ArrayList<>();

        for (AnalysisByDay analysis : lastYearAnalysis) {
            AnalysisChartDataItem item = new AnalysisChartDataItem();
            Integer data = 0;
            String date = DateUtil.format(analysis.getRecordDate(), "yyyy-MM-dd");
            if (type == 101){
                data = analysis.getNumRegistered();
            }else if (type ==102){
                data = analysis.getNumActive();
            }else if (type ==103){
                data = analysis.getNumRetention1d();
            }
            item.setAmount(data.longValue());
            item.setTitle(date);
            lastYearItems.add(item);
        }
        HashMap<String, List> map = new HashMap<>();
        map.put("thisYear",thisYearItems);
        map.put("lastYear",lastYearItems);
        return ResponseEntity.ok(map);
    }


    /**
     * 统计分析日志
     * num_registered：当日新增用户数
     * num_login：当日登录次数
     * num_active：当日活跃用户数
     * num_retention1d：次日留存用户数（前一天注册，第二天继续使用的用户）
     */
    public void analysis() {
        String today = new DateTime().toString("yyyy-MM-dd");
        String yesterday = DateUtil.offsetDay(new Date(), -1).toString("yyyy-MM-dd");
        //num_registered：当日新增用户数
        LambdaQueryWrapper<Log> wrapper = new LambdaQueryWrapper<Log>().eq(Log::getType, "0102").eq(Log::getLogTime, today);
        Integer numRegistered = logMapper.selectCount(wrapper);
        //num_login：当日登录次数
        wrapper = new LambdaQueryWrapper<Log>().eq(Log::getType,"0101").eq(Log::getLogTime,today);
        Integer num_login = logMapper.selectCount(wrapper);
        //num_active：当日活跃用户数
        QueryWrapper<Log> wrapper1 = new QueryWrapper<Log>().select("DISTINCT user_id").eq("log_time", today);
        Integer numActive = logMapper.selectCount(wrapper1);
        //num_retention1d：次日留存用户数（前一天注册，第二天继续使用的用户）
        Integer numRetention = logMapper.queryRetention(today, yesterday);
        AnalysisByDay analysis = summaryMapper.selectOne(new LambdaQueryWrapper<AnalysisByDay>().eq(AnalysisByDay::getRecordDate, today));
        if (analysis==null){
             analysis = new AnalysisByDay();
            analysis.setNumRegistered(numRegistered);
            analysis.setNumLogin(num_login);
            analysis.setNumActive(numActive);
            analysis.setNumRetention1d(numRetention);
            analysis.setCreated(new Date());
            analysis.setUpdated(new Date());
            summaryMapper.insert(analysis);
        }else{
            analysis.setNumRegistered(numRegistered);
            analysis.setNumLogin(num_login);
            analysis.setNumActive(numActive);
            analysis.setNumRetention1d(numRetention);
            analysis.setUpdated(new Date());
            summaryMapper.updateById(analysis);
        }




    }
}
